package com.sinogrand.elevator

import android.os.Bundle
import android.util.Log
import com.sinogrand.elevator.utils.LogTags
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.animation.core.*
import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import android.net.Uri
import androidx.navigation.NavType
import androidx.navigation.navArgument
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.core.tween
import com.sinogrand.elevator.ui.screens.*
import com.sinogrand.elevator.ui.components.ProjectItem
import com.sinogrand.elevator.ui.components.ProjectStatus
import com.sinogrand.elevator.ui.components.ElevatorInfo
import com.sinogrand.elevator.ui.components.ElevatorDetailItem
import com.sinogrand.elevator.ui.theme.Elevator_kotlinTheme
import com.sinogrand.elevator.utils.TokenManager
import com.sinogrand.elevator.utils.AuthStateManager
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import android.content.pm.PackageManager
import android.Manifest
import com.sinogrand.elevator.utils.LocationManager

object Routes {
    const val LOGIN = "login"
    const val HOME = "home"
    const val ELEVATOR_LIST = "elevator_list"
    const val INSTALL = "install"
    const val MAINTENANCE = "maintenance"
    const val PROFILE = "profile"
    const val PROJECT_DETAIL = "project_detail/{projectId}"
    const val SETTINGS = "settings"
    const val ELEVATOR_DETAIL = "elevator_detail/{elevatorId}"
    const val APPROVAL = "approval"
    const val MY_APPROVAL = "my_approval"
    const val MY_WORK_ORDER = "my_work_order"
    const val ENVIRONMENT_SWITCH = "environment_switch"
    const val WEBVIEW_FILE = "webview_file"
}

class MainActivity : ComponentActivity() {
    private lateinit var tokenManager: TokenManager
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        
        tokenManager = TokenManager(this)
        // 初始化全局认证状态管理器
        AuthStateManager.initialize(this)
        
        setContent {
            Elevator_kotlinTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = Color.Transparent
                ) {
                    AppContent()
}
            }
        }
    }
}

@Composable
fun AppContent() {
    val context = androidx.compose.ui.platform.LocalContext.current
    val navController = rememberNavController()
    
    // 定位权限请求器
    val locationPermissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val fineLocationGranted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] ?: false
        val coarseLocationGranted = permissions[Manifest.permission.ACCESS_COARSE_LOCATION] ?: false
        
        Log.i(LogTags.MAIN_ACTIVITY, "🔐 定位权限请求结果:")
        Log.i(LogTags.MAIN_ACTIVITY, "   📍 精确位置权限: $fineLocationGranted")
        Log.i(LogTags.MAIN_ACTIVITY, "   📍 粗略位置权限: $coarseLocationGranted")
        
        if (fineLocationGranted || coarseLocationGranted) {
            Log.i(LogTags.MAIN_ACTIVITY, "✅ 定位权限获取成功，开始获取位置")
            // 初始化定位管理器并开始获取位置
            val locationManager = LocationManager(context)
            locationManager.startLocationUpdates()
        } else {
            Log.w(LogTags.MAIN_ACTIVITY, "⚠️ 定位权限被拒绝")
        }
    }
    
    // 在应用启动时请求定位权限
    LaunchedEffect(Unit) {
        val fineLocationPermission = ContextCompat.checkSelfPermission(
            context, 
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
        
        val coarseLocationPermission = ContextCompat.checkSelfPermission(
            context, 
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
        
        Log.d(LogTags.MAIN_ACTIVITY, "🔐 检查定位权限状态:")
        Log.d(LogTags.MAIN_ACTIVITY, "   📍 精确位置权限: $fineLocationPermission")
        Log.d(LogTags.MAIN_ACTIVITY, "   📍 粗略位置权限: $coarseLocationPermission")
        
        if (!fineLocationPermission && !coarseLocationPermission) {
            Log.i(LogTags.MAIN_ACTIVITY, "🔐 请求定位权限...")
            locationPermissionLauncher.launch(
                arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
                )
            )
        } else {
            Log.i(LogTags.MAIN_ACTIVITY, "✅ 定位权限已获取，开始获取位置")
            // 初始化定位管理器并开始获取位置
            val locationManager = LocationManager(context)
            locationManager.startLocationUpdates()
        }
    }
    
    // 使用全局认证状态管理器
    val isLoggedIn by AuthStateManager.isLoggedIn.collectAsState()
    
    NavHost(
        navController = navController,
        startDestination = if (isLoggedIn) Routes.HOME else Routes.LOGIN
    ) {
        composable(Routes.LOGIN) {
            LoginScreen(
                onLoginSuccess = {
                    // 登录成功，通知全局状态管理器
                    AuthStateManager.login()
                },
                onNavigateToEnvironmentSwitch = {
                    // 导航到环境切换页面
                    navController.navigate(Routes.ENVIRONMENT_SWITCH)
                }
            )
        }
        composable(Routes.ENVIRONMENT_SWITCH) {
            EnvironmentSwitchScreen(
                onNavigateBack = {
                    navController.popBackStack()
                },
                onEnvironmentChanged = {
                    // 环境切换后，清除网络缓存并返回登录页面
                    com.sinogrand.elevator.network.NetworkClient.clearCache()
                    AuthStateManager.logout()
                }
            )
        }
        composable(Routes.HOME) {
            MainScreen(
                onLogout = {
                    AuthStateManager.logout()
                }
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreen(
    onLogout: () -> Unit = {}
) {
    val navController = rememberNavController()
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentRoute = navBackStackEntry?.destination?.route ?: Routes.HOME

    val bottomNavItems = listOf(
        BottomNavItem("首页", Icons.Filled.Home, Routes.HOME),
        BottomNavItem("安装", Icons.Filled.Settings, Routes.INSTALL),
        BottomNavItem("维保", Icons.Filled.Warning, Routes.MAINTENANCE),
        BottomNavItem("我的", Icons.Filled.Person, Routes.PROFILE)
    )

    // 判断是否为详情页面，详情页面不显示TabBar
    val isDetailScreen = currentRoute != Routes.HOME && currentRoute != Routes.INSTALL && currentRoute != Routes.MAINTENANCE && currentRoute != Routes.PROFILE

    Scaffold(
        modifier = Modifier.fillMaxSize(),
        bottomBar = {
            if (!isDetailScreen) {
                BeautifulTabBar(
                    navItems = bottomNavItems,
                    currentRoute = currentRoute,
                    onNavigate = { route ->
                        navController.navigate(route) {
                            popUpTo(navController.graph.startDestinationId) {
                                saveState = true
                            }
                            launchSingleTop = true
                            restoreState = true
                        }
                    }
                )
            }
        }
    ) { innerPadding ->
        NavHost(
            navController = navController,
            startDestination = Routes.HOME
        ) {
            composable(Routes.HOME) {
                HomeScreen(
                    onNavigateToElevatorList = {
                        navController.navigate(Routes.ELEVATOR_LIST)
                    },
                    onNavigateToElevatorDetail = { elevator ->
                        Log.d(LogTags.HOME_SCREEN, "点击电梯: elevatorId=${elevator.id}")
                        navController.navigate("elevator_detail/${elevator.id}")
                    },
                    onNavigateToApproval = { formId ->
                        navController.navigate("${Routes.APPROVAL}?formId=$formId")
                    }
                )
            }
            composable(
                route = Routes.ELEVATOR_LIST,
                enterTransition = {
                    slideInHorizontally(
                        initialOffsetX = { fullWidth -> fullWidth },
                        animationSpec = tween(300)
                    ) + fadeIn(animationSpec = tween(300))
                },
                exitTransition = {
                    slideOutHorizontally(
                        targetOffsetX = { fullWidth -> -fullWidth },
                        animationSpec = tween(300)
                    ) + fadeOut(animationSpec = tween(300))
                },
                popEnterTransition = {
                    slideInHorizontally(
                        initialOffsetX = { fullWidth -> -fullWidth },
                        animationSpec = tween(300)
                    ) + fadeIn(animationSpec = tween(300))
                },
                popExitTransition = {
                    slideOutHorizontally(
                        targetOffsetX = { fullWidth -> fullWidth },
                        animationSpec = tween(300)
                    ) + fadeOut(animationSpec = tween(300))
                }
            ) {
                ElevatorListScreen(
                    onBackClick = {
                        navController.popBackStack()
                    },
                    onElevatorClick = { elevator ->
                        Log.d(LogTags.ELEVATOR_LIST, "点击电梯: elevatorId=${elevator.id}")
                        navController.navigate("elevator_detail/${elevator.id}")
                    }
                )
            }
            composable(Routes.INSTALL) {
                InstallScreen(
                    paddingValues = innerPadding,
                    onNavigateToProjectDetail = { projectId ->
                        navController.navigate("project_detail/$projectId")
                    }
                )
            }
            composable(Routes.MAINTENANCE) {
                MaintenanceScreen(
                    paddingValues = innerPadding,
                    onNavigateToProjectDetail = { projectId ->
                        navController.navigate("project_detail/$projectId")
                    }
                )
            }
            composable(Routes.PROFILE) {
                ProfileScreen(
                    onNavigateToSettings = {
                        navController.navigate(Routes.SETTINGS)
                    },
                    onNavigateToMyApproval = {
                        navController.navigate(Routes.MY_APPROVAL)
                    },
                    onNavigateToMyWorkOrder = {
                        navController.navigate(Routes.MY_WORK_ORDER)
                    }
                )
            }
            composable(
                route = Routes.SETTINGS,
                enterTransition = {
                    slideInHorizontally(
                        initialOffsetX = { fullWidth -> fullWidth },
                        animationSpec = tween(300)
                    ) + fadeIn(animationSpec = tween(300))
                },
                exitTransition = {
                    slideOutHorizontally(
                        targetOffsetX = { fullWidth -> -fullWidth },
                        animationSpec = tween(300)
                    ) + fadeOut(animationSpec = tween(300))
                },
                popEnterTransition = {
                    slideInHorizontally(
                        initialOffsetX = { fullWidth -> -fullWidth },
                        animationSpec = tween(300)
                    ) + fadeIn(animationSpec = tween(300))
                },
                popExitTransition = {
                    slideOutHorizontally(
                        targetOffsetX = { fullWidth -> fullWidth },
                        animationSpec = tween(300)
                    ) + fadeOut(animationSpec = tween(300))
                }
            ) {
                SettingsScreen(
                    onBackClick = {
                        navController.popBackStack()
                    },
                    onLogout = onLogout
                )
            }
            composable(Routes.MY_APPROVAL) {
                MyApprovalScreen(
                    onNavigateBack = {
                        navController.popBackStack()
                    },
                    onNavigateToApproval = { formId ->
                        navController.navigate("${Routes.APPROVAL}?formId=$formId")
                    }
                )
            }
            composable(Routes.MY_WORK_ORDER) {
                MyWorkOrderScreen(
                    onNavigateBack = {
                        navController.popBackStack()
                    },
                    onNavigateToWorkOrder = { _ ->
                        // TODO: 这里可以导航到工单详情页面
                        // navController.navigate("${Routes.WORK_ORDER_DETAIL}?formId=$formId")
                    }
                )
            }
            composable(
                route = "${Routes.APPROVAL}?formId={formId}&templateId={templateId}&projectId={projectId}&elevatorId={elevatorId}",
                arguments = listOf(
                    navArgument("formId") { 
                        type = NavType.IntType
                        defaultValue = 0
                    },
                    navArgument("templateId") { 
                        type = NavType.IntType
                        defaultValue = 0
                    },
                    navArgument("projectId") { 
                        type = NavType.IntType
                        defaultValue = 0
                    },
                    navArgument("elevatorId") { 
                        type = NavType.IntType
                        defaultValue = 0
                    }
                ),
                enterTransition = {
                    slideInHorizontally(
                        initialOffsetX = { fullWidth -> fullWidth },
                        animationSpec = tween(300)
                    ) + fadeIn(animationSpec = tween(300))
                },
                exitTransition = {
                    slideOutHorizontally(
                        targetOffsetX = { fullWidth -> -fullWidth },
                        animationSpec = tween(300)
                    ) + fadeOut(animationSpec = tween(300))
                },
                popEnterTransition = {
                    slideInHorizontally(
                        initialOffsetX = { fullWidth -> -fullWidth },
                        animationSpec = tween(300)
                    ) + fadeIn(animationSpec = tween(300))
                },
                popExitTransition = {
                    slideOutHorizontally(
                        targetOffsetX = { fullWidth -> fullWidth },
                        animationSpec = tween(300)
                    ) + fadeOut(animationSpec = tween(300))
                }
            ) { backStackEntry ->
                Log.d(LogTags.MAIN_ACTIVITY, "🔍 ApprovalScreen路由参数调试:")
                Log.d(LogTags.MAIN_ACTIVITY, "   📋 所有参数: ${backStackEntry.arguments?.keySet()}")
                
                // 从navArgument获取参数
                val formId = backStackEntry.arguments?.getInt("formId") ?: 0
                val templateId = backStackEntry.arguments?.getInt("templateId") ?: 0
                val projectId = backStackEntry.arguments?.getInt("projectId") ?: 0
                val elevatorId = backStackEntry.arguments?.getInt("elevatorId") ?: 0
                
                Log.d(LogTags.MAIN_ACTIVITY, "   🔢 formId参数: $formId")
                Log.d(LogTags.MAIN_ACTIVITY, "   📄 templateId参数: $templateId")
                Log.d(LogTags.MAIN_ACTIVITY, "   🏗️ projectId参数: $projectId")
                Log.d(LogTags.MAIN_ACTIVITY, "   🛗 elevatorId参数: $elevatorId")
                
                // 处理默认值0的情况，转换为null
                val finalFormId = if (formId == 0) null else formId
                val finalTemplateId = if (templateId == 0) null else templateId
                val finalProjectId = if (projectId == 0) null else projectId
                val finalElevatorId = if (elevatorId == 0) null else elevatorId
                
                Log.d(LogTags.MAIN_ACTIVITY, "   ✅ 最终参数 - formId: $finalFormId, templateId: $finalTemplateId, projectId: $finalProjectId, elevatorId: $finalElevatorId")
                
                ApprovalScreen(
                    onNavigateBack = {
                        navController.popBackStack()
                    },
                    formId = finalFormId,
                    templateId = finalTemplateId,
                    projectId = finalProjectId,
                    elevatorId = finalElevatorId,
                    onNavigateToFileViewer = { fileUrl, fileName ->
                        navController.navigate("${Routes.WEBVIEW_FILE}?url=${Uri.encode(fileUrl)}&title=${Uri.encode(fileName)}")
                    }
                )
            }
            composable(
                route = "${Routes.WEBVIEW_FILE}?url={url}&title={title}",
                arguments = listOf(
                    navArgument("url") { 
                        type = NavType.StringType
                        defaultValue = ""
                    },
                    navArgument("title") { 
                        type = NavType.StringType
                        defaultValue = "文件查看"
                    }
                ),
                enterTransition = {
                    slideInHorizontally(
                        initialOffsetX = { fullWidth -> fullWidth },
                        animationSpec = tween(300)
                    ) + fadeIn(animationSpec = tween(300))
                },
                exitTransition = {
                    slideOutHorizontally(
                        targetOffsetX = { fullWidth -> -fullWidth },
                        animationSpec = tween(300)
                    ) + fadeOut(animationSpec = tween(300))
                },
                popEnterTransition = {
                    slideInHorizontally(
                        initialOffsetX = { fullWidth -> -fullWidth },
                        animationSpec = tween(300)
                    ) + fadeIn(animationSpec = tween(300))
                },
                popExitTransition = {
                    slideOutHorizontally(
                        targetOffsetX = { fullWidth -> fullWidth },
                        animationSpec = tween(300)
                    ) + fadeOut(animationSpec = tween(300))
                }
            ) { backStackEntry ->
                val fileUrl = backStackEntry.arguments?.getString("url") ?: ""
                val fileName = backStackEntry.arguments?.getString("title") ?: "文件查看"
                
                FileViewerScreen(
                    fileUrl = fileUrl,
                    fileName = fileName,
                    onNavigateBack = {
                        navController.popBackStack()
                    }
                )
            }
            composable(
                route = Routes.ELEVATOR_DETAIL,
                enterTransition = {
                    slideInHorizontally(
                        initialOffsetX = { fullWidth -> fullWidth },
                        animationSpec = tween(300)
                    ) + fadeIn(animationSpec = tween(300))
                },
                exitTransition = {
                    slideOutHorizontally(
                        targetOffsetX = { fullWidth -> -fullWidth },
                        animationSpec = tween(300)
                    ) + fadeOut(animationSpec = tween(300))
                },
                popEnterTransition = {
                    slideInHorizontally(
                        initialOffsetX = { fullWidth -> -fullWidth },
                        animationSpec = tween(300)
                    ) + fadeIn(animationSpec = tween(300))
                },
                popExitTransition = {
                    slideOutHorizontally(
                        targetOffsetX = { fullWidth -> fullWidth },
                        animationSpec = tween(300)
                    ) + fadeOut(animationSpec = tween(300))
                }
            ) { backStackEntry ->
                val elevatorIdString = backStackEntry.arguments?.getString("elevatorId") ?: "0"
                val elevatorId = elevatorIdString.toIntOrNull() ?: 0
                ElevatorDetailScreen(
                    elevatorId = elevatorId,
                    onBackClick = {
                        navController.popBackStack()
                    },
                    onNavigateToApproval = { formId, elevatorIdParam, projectId ->
                        navController.navigate("${Routes.APPROVAL}?formId=$formId&elevatorId=$elevatorIdParam&projectId=$projectId")
                    },
                    onNavigateToApprovalWithTemplate = { templateId, elevatorIdParam, projectId ->
                        navController.navigate("${Routes.APPROVAL}?templateId=$templateId&elevatorId=$elevatorIdParam&projectId=$projectId")
                    }
                )
            }
            composable(
                route = Routes.PROJECT_DETAIL,
                enterTransition = {
                    slideInHorizontally(
                        initialOffsetX = { fullWidth -> fullWidth },
                        animationSpec = tween(300)
                    ) + fadeIn(animationSpec = tween(300))
                },
                exitTransition = {
                    slideOutHorizontally(
                        targetOffsetX = { fullWidth -> -fullWidth },
                        animationSpec = tween(300)
                    ) + fadeOut(animationSpec = tween(300))
                },
                popEnterTransition = {
                    slideInHorizontally(
                        initialOffsetX = { fullWidth -> -fullWidth },
                        animationSpec = tween(300)
                    ) + fadeIn(animationSpec = tween(300))
                },
                popExitTransition = {
                    slideOutHorizontally(
                        targetOffsetX = { fullWidth -> fullWidth },
                        animationSpec = tween(300)
                    ) + fadeOut(animationSpec = tween(300))
                }
            ) { backStackEntry ->
                val projectId = backStackEntry.arguments?.getString("projectId") ?: ""
                val project = getProjectById(projectId) // 需要实现这个函数
                ProjectDetailScreen(
                    project = project,
                    onBackClick = {
                        navController.popBackStack()
                    },
                    onElevatorClick = { elevator ->
                        // 传递电梯ID
                        Log.d(LogTags.ELEVATOR_DETAIL, "点击电梯: elevatorId=${elevator.id}")
                        navController.navigate("elevator_detail/${elevator.id}")
                    }
                )
            }
        }
    }
}

data class BottomNavItem(
    val title: String,
    val icon: ImageVector,
    val route: String
)

@Composable
fun BeautifulTabBar(
    navItems: List<BottomNavItem>,
    currentRoute: String,
    onNavigate: (String) -> Unit
) {
    val infiniteTransition = rememberInfiniteTransition(label = "tabBar")
    val pulseAnimation by infiniteTransition.animateFloat(
        initialValue = 0.95f,
        targetValue = 1.05f,
        animationSpec = infiniteRepeatable(
            animation = tween(2000, easing = EaseInOutSine),
            repeatMode = RepeatMode.Reverse
        ),
        label = "pulse"
    )
    
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .windowInsetsPadding(WindowInsets.navigationBars)
            .shadow(
                elevation = 16.dp,
                shape = RectangleShape,
                ambientColor = Color(0xFF3B82F6).copy(alpha = 0.2f),
                spotColor = Color(0xFF60A5FA).copy(alpha = 0.1f)
            ),
        shape = RectangleShape,
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.95f)
        )
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .background(
                    brush = Brush.linearGradient(
                        colors = listOf(
                            Color.White.copy(alpha = 0.9f),
                            Color(0xFFF8FAFC).copy(alpha = 0.8f)
                        )
                    )
                )
                .padding(vertical = 8.dp, horizontal = 16.dp),
            horizontalArrangement = Arrangement.SpaceEvenly,
            verticalAlignment = Alignment.CenterVertically
        ) {
            navItems.forEach { navItem ->
                BeautifulTabItem(
                    navItem = navItem,
                    isSelected = currentRoute == navItem.route,
                    onClick = { onNavigate(navItem.route) },
                    pulseScale = if (currentRoute == navItem.route) pulseAnimation else 1f
                )
            }
        }
    }
}

@Composable
fun BeautifulTabItem(
    navItem: BottomNavItem,
    isSelected: Boolean,
    onClick: () -> Unit,
    pulseScale: Float = 1f
) {
    val animatedScale by animateFloatAsState(
        targetValue = if (isSelected) pulseScale else 1f,
        animationSpec = tween(300, easing = EaseOutCubic),
        label = "scale"
    )
    
    val animatedColor by animateColorAsState(
        targetValue = if (isSelected) Color(0xFF3B82F6) else Color(0xFF6B7280),
        animationSpec = tween(300, easing = EaseOutCubic),
        label = "color"
    )
    
    val animatedBackgroundColor by animateColorAsState(
        targetValue = if (isSelected) Color(0xFF3B82F6).copy(alpha = 0.1f) else Color.Transparent,
        animationSpec = tween(300, easing = EaseOutCubic),
        label = "backgroundColor"
    )
    
    Box(
        modifier = Modifier
            .scale(animatedScale)
            .clip(RoundedCornerShape(16.dp))
            .background(color = animatedBackgroundColor)
            .clickable { onClick() }
            .padding(horizontal = 12.dp, vertical = 8.dp),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Icon(
                imageVector = navItem.icon,
                contentDescription = navItem.title,
                tint = animatedColor,
                modifier = Modifier.size(24.dp)
            )
            Spacer(modifier = Modifier.height(4.dp))
            Text(
                text = navItem.title,
                color = animatedColor,
                fontSize = 12.sp,
                fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium
            )
        }
    }
}

// 根据项目ID获取项目信息的函数
fun getProjectById(projectId: String): ProjectItem {
    // 这里应该从数据库或API获取项目信息
    // 现在返回一个模拟的项目数据
    return ProjectItem(
        id = projectId,
        name = "项目详情 - $projectId",
        description = "这是一个项目详情页面的示例项目",
        status = ProjectStatus.IN_PROGRESS,
        imageUrl = "https://picsum.photos/200/200?random=$projectId"
    )
}

// 根据电梯ID获取电梯信息的函数
fun getElevatorInfoById(elevatorId: String): ElevatorInfo {
    // 这里应该从数据库或API获取电梯信息
    // 现在返回一个模拟的电梯数据
    Log.d(LogTags.ELEVATOR_DETAIL, "模拟获取电梯信息: elevatorId=$elevatorId")
    
    return ElevatorInfo(
        id = elevatorId.toIntOrNull() ?: 0,
        name = "电梯_${elevatorId}",
        no = elevatorId,
        sn = "SN${elevatorId}",
        type = 1,
        install_type = "无脚手架",
        brand = "品牌${elevatorId}",
        model = "型号${elevatorId}",
        unit_price = 50000.0,
        start_date = "2025-09-09",
        end_date = "2025-09-26",
        details = listOf(
            ElevatorDetailItem("elevator_no", "梯号", elevatorId.toString()),
            ElevatorDetailItem("elevator_sn", "出厂编号", "SN${elevatorId}"),
            ElevatorDetailItem("elevator_name", "设备名称", "电梯_${elevatorId}"),
            ElevatorDetailItem("elevator_install_type", "安装类型", "无脚手架"),
            ElevatorDetailItem("elevator_brand", "品牌", "品牌${elevatorId}"),
            ElevatorDetailItem("elevator_model", "型号", "型号${elevatorId}"),
            ElevatorDetailItem("elevator_start_date", "开始时间", "2025-09-09"),
            ElevatorDetailItem("elevator_end_date", "结束时间", "2025-09-26"),
            ElevatorDetailItem("elevator_unit_price", "承揽安装单价（万元）", "5"),
            ElevatorDetailItem("9M8wGnq3tIOEOLQc", "载重（kg）/梯级宽度（mm）", "1000/1000"),
            ElevatorDetailItem("BBk1fHsgeLFhxTPp", "速度（m/s）", "1.0"),
            ElevatorDetailItem("aTNgfD8H17qgZTfP", "层/站/门倾斜角", "10/10/30°"),
            ElevatorDetailItem("W2aeKyMgrTE5S0zE", "提升高度（m）", "30"),
            ElevatorDetailItem("opT7iNd0nym8VJkH", "跨距（mm）", "2000"),
            ElevatorDetailItem("ZcxWHAQEmYylMN2a", "扶梯安装位置", "室内"),
            ElevatorDetailItem("qP4DcsUJVL3q5Cvo", "井道尺寸（宽*深mm）", "2000*2000"),
            ElevatorDetailItem("A72FMwVrDGbTX6si", "基坑深度（mm）", "1000"),
            ElevatorDetailItem("aWINO8i5lpl3DCIF", "顶层高度（mm）", "3500"),
            ElevatorDetailItem("qkuDoorybHafhczp", "开门尺寸（宽*深mm）", "800*2000"),
            ElevatorDetailItem("GjawX37S7iR9YeuR", "开门方式", "中分"),
            ElevatorDetailItem("85iT9BXgOkvWpYgG", "轿厢尺寸（宽*深*高mm）", "1600*1400*2200"),
            ElevatorDetailItem("wBia5i5GAMJd4btI", "预留装潢", "是"),
            ElevatorDetailItem("qc1K835aSuYL948c", "无障碍配置", "是"),
            ElevatorDetailItem("FiTg7omKArMgcKPo", "备注", "测试电梯")
        ),
        status = 1,
        created_at = "2025-09-18 15:49:39",
        updated_at = "2025-09-18 15:49:39"
    )
}


@Preview(showBackground = true)
@Composable
fun MainScreenPreview() {
    Elevator_kotlinTheme {
        MainScreen()
    }
}